<?php
/**
 * Created by PhpStorm.
 * User: JHR
 * Date: 2018/9/27
 * Time: 11:24
 */
namespace app\manage\controller;
use my\MyRedis;
use think\facade\Db;
use think\exception\HttpResponseException;
use think\facade\Cache;

class Login extends Base {

    private function fail_alarm($action,$username) {
        $key = $username;
        $ttl = 600;
        $exist = Cache::get($username);
        if($action === "check") {
            if ($exist) {
                if($exist['fail_times']>=5) {
                    trigger_error("失败次数太多,请稍后再试!",E_USER_ERROR);
                }
            }
        }else {
            if ($exist) {
                Cache::set($key,[
                    'fail_times' => $exist['fail_times']+1,
                    'last_fail_time' => time()
                ],$ttl);
            }else {
                Cache::set($key,[
                    'fail_times' => 1,
                    'last_fail_time' => time()
                ],$ttl);
            }
        }
    }

    public function login() {
        $post['username'] = input('post.username');
        $post['password'] = input('post.password');
        checkPost($post);
        $where = [
            ['username','=',$post['username']],
            ['password','=',md5($post['password'] . config('app.login_key'))]
        ];
        if(!validate_password_v2($post['password'])) {
            return ajax('',-1,'密码格式不符!至少包含大小写字母、数字和特殊符号中的三种');
        }
        $this->fail_alarm("check",$post['username']);
        try {
            $result = Db::table('mp_admin')->where($where)->field('id AS admin_id,realname,username,avatar,email,status,role,last_login_province')->find();
            if(!$result) {
                $this->fail_alarm("set",$post['username']);
                return ajax('用户名密码不匹配',51);
            }else {
                if($result['status'] === 2 && $result['admin_id'] !== 1) {
                    return ajax('账号已冻结',55);
                }
                $noncestr = randomkeys(6);
                $time = time();
                $token = md5($result['admin_id'] . $noncestr . $time);
                $ip = $this->getip();
                $insert_data = [
                    'admin_id' => $result['admin_id'],
                    'role' => $result['role'],
                    'token' => $token,
                    'ip' => $ip,
                    'create_time' => $time,
                    'login_type' => 5,
                ];
                Db::table('mp_admin_token')->insert($insert_data);
                $log_data = [
                    'type' => 0,
                    'admin_id' => $result['admin_id'],
                    'ip' => $ip,
                    'create_time' => $time,
                    'login_type' => 5,
                ];
                Db::table('mp_syslog')->insert($log_data);
                Db::table('mp_admin')->where($where)->update([
                    'last_login_time' => $time,
                    'last_login_ip' => $ip,
                ]);
            }
        }catch (\Exception $e) {
            return ajax($e->getMessage(),-1,$e->getMessage());
        }
        $result['token'] = $token;
        return ajax($result);
    }

    public function checkToken() {
        $token = input('post.token');
        try {
            if(!$token) {
                return ajax('请传入token',-3);
            }else {
                $whereToken = [
                    ['token','=',$token]
                ];
                $token_exist = Db::table('mp_admin_token')->where($whereToken)->find();
                if(!$token_exist) {
                    return ajax('token无效',-3);
                }else {
                    if((time() - $token_exist['create_time']) > config('app.token_expires_time')) {
                        return ajax('token已过期',-3);
                    }
                }
            }
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }

    protected function getip() {
        $unknown = 'unknown';
        if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown) ) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif ( isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown) ) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        /*
        处理多层代理的情况
        或者使用正则方式：$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;
        */
        if (false !== strpos($ip, ',')) {
            $ip_arr = explode(',', $ip);
            $ip = reset($ip_arr);
        }
        return $ip;
    }




}